package com.demo.rabbitmq.consumer;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

/**
 * <a href="https://blog.csdn.net/sun_tantan/article/details/88667102">关于手动ack说明</a>
 * 验证消息消费失败，RabbitMQ会不会把消息转移到另一个消费者消费。这里实现了RabbitMQ的公平分配消息
 */
@Slf4j
@Service
public class ExceptionConsumer {

    /**
     * 消费失败，返回nack，消息重回队列，等待下次消费
     * @param message 消息
     * @param channel RabbitMQ Channel
     * @throws Exception 消费异常
     */
    @RabbitListener(id = "direct_exception_queue", queues = "direct_exception_queue")
    public void exception(Message message, Channel channel) throws Exception {
        try {
            throw new Exception("消费者1，内容：" + new String(message.getBody()));
        } catch (Exception e) {
            log.error(e.getMessage());
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
        }
    }

    /**
     * 消费成功
     * @param message 消息
     * @param channel RabbitMQ Channel
     * @throws Exception 消费异常
     */
    @RabbitListener(id = "direct_exception_queue1", queues = "direct_exception_queue")
    public void exception1(Message message, Channel channel) throws Exception {
        log.info("消费者2，内容：" + new String(message.getBody()));
        channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }
}
